package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {

    @Autowired
    private ICategorySafeguardService categorySafeguardService;

    @Autowired
    private IPlanSafeguardService planSafeguardService;

    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {

        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(safeguardVO));

        return BeanConv.toPage(page, SafeguardVO.class);
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO
        return null;
    }

    @Override
    @Caching(
        put = @CachePut(value = SafeguardCacheConstant.BASIC, key = "#result.id"),
        evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)
        }
    )
    @Transactional(rollbackFor = Exception.class)
    public SafeguardVO save(SafeguardVO safeguardVO) {

        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();

        if(count > 0){
            log.error("该key已存在");
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }

        Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);

        this.save(safeguard);

        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }

    @Override
    @Transactional
    @Caching(
            put = @CachePut(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id"),
            evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)
    })
    public Boolean update(SafeguardVO safeguardVO) {

        // 判断id是否存在
        Safeguard bean = getById(safeguardVO.getId());
        if(bean==null){
            log.error("该保障项不存在");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }

        // 判断该key除自己以外是否存在
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())
                .count();

        if(count>0){
            log.error("该key已存在");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }

        // 判断 分类保障项&方案保障项 关系表是否存在关联项
        int count1 = judgeMiddleTableDataExist(safeguardVO.getSafeguardKey());

        if(count1 > 0){
            log.error("该保障项已被关联，无法修改");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }

        return updateById(BeanConv.toBean(safeguardVO, Safeguard.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)
    })
    public Boolean delete(String[] checkedIds) {

        // 判断是否存在
        Safeguard bean = getById(checkedIds[0]);
        if(bean==null){
            log.error("删除失败，该数据不存在");
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }

        // 判断 分类保障项&方案保障项 关系表是否存在关联项
        int count1 = judgeMiddleTableDataExist(bean.getSafeguardKey());

        if(count1 > 0){
            log.error("该保障项已被关联，无法删除");
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }

        int result = baseMapper.deleteById(bean.getId());

        return result > 0;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#result.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {

        List<Safeguard> list = this.list(queryWrapper(safeguardVO));

        return list.stream().map(s->BeanConv.toBean(s, SafeguardVO.class)).collect(Collectors.toList());
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }

    /**
     * 分页 list 共用的wrapper
     * @param safeguardVO
     * @return
     */
    private LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO){
        LambdaQueryWrapper<Safeguard> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());
        return lqw;
    }

    /**
     * 判断 分类保障项 & 方案保障项 关系表是否存在关联项
     * @param safeguardKey
     * @return
     */
    private int judgeMiddleTableDataExist(String safeguardKey){
        // 判断分类保障项是否存在关联项
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardKey)
                .count();

        // 判断方案保障项关系表是否存在关联项
        Integer count2 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardKey)
                .count();

        if(count1>0 || count2>0){
            return 1;
        }
        return 0;
    }
}
